<template>
  <img
    ref="target"
    v-bind="$attrs"
    class="img"
    :src="defaultImage"
    alt="image"
    @error="setDefaultImage"
  />
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue';
import { useIntersectionObserver } from '@vueuse/core';

interface Props {
  src?: string;
}
const props = withDefaults(defineProps<Props>(), {
  src: ''
});

const target = ref<HTMLImageElement | null>(null);
useIntersectionObserver(target, ([{ isIntersecting }]) => {
  if (isIntersecting) {
    if (target.value) {
      target.value.src = props.src;
    }
  }
});

const defaultImage = 'https://cdn.kaogujia.com/kgj-3.0-pc/ui/null_img_z.svg';

function setDefaultImage(event: any) {
  event.target.src = defaultImage;
}

watch(
  () => props.src,
  (value) => {
    if (target.value) {
      if (value) {
        target.value.src = value;
      } else {
        target.value.src =
          'https://cdn.kaogujia.com/kgj-3.0-pc/ui/null_img_z.svg';
      }
    }
  },
  {
    immediate: true,
    deep: true
  }
);
</script>

<style lang="scss" scoped>
.img {
  width: 40px;
  height: 40px;
}
</style>
